package org.sgy.mall.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadTestServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//resp.setHeader("Content-disposition", "attachment;filename=test.png");
		File file = new File("C:\\Users\\lenovo\\Desktop\\test.jpg");
		FileInputStream input = new FileInputStream(file);
		ServletOutputStream output = resp.getOutputStream();
		byte[] buffer = new byte[1024];
		int read;
		while ((read = input.read(buffer)) > 0) {
			if (read < buffer.length) {
				output.write(buffer, 0, read);
				output.flush();
			} else {
				output.write(buffer);
				output.flush();
			}
		}
		output.flush();
		output.close();
		input.close();
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		boolean isMultipart = ServletFileUpload.isMultipartContent(req);
		if (isMultipart) {
			DiskFileItemFactory factory = new DiskFileItemFactory();
			// Create a new file upload handler
			ServletFileUpload upload = new ServletFileUpload(factory);
			// Parse the request
			try {
				List<FileItem> items = upload.parseRequest(req);

				Iterator<FileItem> iter = items.iterator();
				while (iter.hasNext()) {
					FileItem item = iter.next();
					if (item.isFormField()) {
						System.out.println(item.getName() + ":" + new String(item.get()));
					} else {
						// File file = new File("C:\\Users\\lenovo\\Desktop\\test.jpg");
						File file = new File("C:\\Users\\lenovo\\Desktop\\test.pptx");
						item.write(file);
					}
				}
			} catch (FileUploadException e) {
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
